package com.smartglass.alfareallive;

import android.content.Context;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.io.Serializable;

/**
 * Created by yangfei on 2016/9/6.
 */

public class LiveParamUtils implements Serializable {
    private static final long serialVersionUID = -7060210544600464481L;

    public final String LIVE_PARAM = "alfa_live_param";

    public String Alfa_Url = null;
    public int Alfa_videoformat_W = 768;
    public int Alfa_videoformat_H = 432;
    public int Alfa_framerate = 24;
    public int Alfa_bitrate_min = 200000;
    public int Alfa_bitrate_max = 8000000;
    public int Alfa_strategy = 1;

    //默认直播参数
    private String PUSH_URL = null;
    private final int RESOLUTION = 4;
    private final int ALFA_FRAMERATE = 15;
    private final int ALFA_BITRATE_MIN = 3000000;
    private final int ALFA_BITRATE_MAX = 8000000;
    private final int ALFA_STRATEGY = 2;

    public String mPushUrl;
    public String mPlayUrl;

    public LiveParamUtils(Context ctx){
        createPushUrl(ctx);
    }

    public void writeSDFile(String fileName, String write_str) {
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = write_str.getBytes();
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // read file
    public String readSDFile(String fileName) {
        String token = null;

        try {
            FileInputStream fis;
            String filePath = Environment.getExternalStorageDirectory() + "/" + fileName;
            File f = new File(filePath);
            if (!f.exists()) {
                return null;
            }
            fis = new FileInputStream(f);
            int length = fis.available();
            byte[] buffer = new byte[length];
            fis.read(buffer);
            token = EncodingUtils.getString(buffer, "UTF-8");
            fis.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return token;
    }

    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }


    public String setDefaultLiveParam(Context ctx){
        JSONObject object = new JSONObject();
        try {
            object.put("push_url",PUSH_URL);
            object.put("resolution",RESOLUTION);
            object.put("frame",ALFA_FRAMERATE);
            object.put("min_kbyte",ALFA_BITRATE_MIN);
            object.put("max_kbyte",ALFA_BITRATE_MAX);
            object.put("strategy",ALFA_STRATEGY);
            Log.d("organizeParam",object.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String liveParamStr = object.toString();
        Settings.System.putString(ctx.getContentResolver(), LIVE_PARAM, liveParamStr);
        return liveParamStr;
    }

    private void createPushUrl(Context ctx){
        String snStr = Settings.System.getString(ctx.getContentResolver(), "phone_serial");

        String pushBaseUrl = "://3546.mpush.live.lecloud.com/live/"+snStr;
        String pullBaseUrl = "://3546.mpull.live.lecloud.com/live/"+snStr;

        String AlfaPlayPageUrl= "http://www.alfareal.com/wx/live.php?videourl=";
        mPushUrl = "rtmp"+pushBaseUrl;
        PUSH_URL = mPushUrl;

//        mPlayUrl = AlfaPlayPageUrl + "http"+pullBaseUrl+"/desc.m3u8";
        mPlayUrl = "http"+pullBaseUrl+"/desc.m3u8";
    }

    /**
     * 从SystemSetting中读取并使用gson解析参数
     *
     * @return
     */
    public boolean readConfig(String liveParam) {
        Log.d("liveParam", liveParam);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(liveParam);
            Alfa_Url = jsonObject.optString("push_url");
            int resolutionRate = jsonObject.optInt("resolution");
            switch (resolutionRate) {
                case 1:
                    Alfa_videoformat_W = 480;
                    Alfa_videoformat_H = 320;
                    break;
                case 2:
                    Alfa_videoformat_W = 480;
                    Alfa_videoformat_H = 352;
                    break;
                case 3:
                    Alfa_videoformat_W = 640;
                    Alfa_videoformat_H = 352;
                    break;
                case 4:
                    Alfa_videoformat_W = 768;
                    Alfa_videoformat_H = 432;
                    break;
                case 5:
                    Alfa_videoformat_W = 1280;
                    Alfa_videoformat_H = 720;
                    break;
            }
            Alfa_framerate = jsonObject.optInt("frame");
            Alfa_bitrate_min = jsonObject.optInt("min_kbyte");
            Alfa_bitrate_max = jsonObject.optInt("max_kbyte");
            Alfa_strategy = jsonObject.optInt("strategy");


            //保存配置文件给底层的库调用
            String paraStr = "Alfa_Url=" + Alfa_Url +
                    "\r\nAlfa_videoformat_W=" + Alfa_videoformat_W +
                    "\r\nAlfa_videoformat_H=" + Alfa_videoformat_H +
                    "\r\nAlfa_framerate=" + Alfa_framerate +
                    "\r\nAlfa_bitrate_min=" + Alfa_bitrate_min +
                    "\r\nAlfa_bitrate_max=" + Alfa_bitrate_max +
                    "\r\nAlfa_strategy=" + Alfa_strategy +
                    "\r\n";

            deleteFile("/sdcard/rtmp.cfg");
            writeSDFile("rtmp.cfg", paraStr);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return true;
    }
}
